import editForm from "../form.vue";
import upload from "../upload.vue";
import {
  type Employee,
  addEmployee,
  updateEmployee,
  deleteEmployee,
  getEmployeeList,
  leaveEmployee
} from "@/api/employee";
import { addDialog, closeDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { DictTag } from "@/components/ReDict";
import { getJobList } from "@/api/job";
import { getDeptList } from "@/api/dept";
import { handleTree } from "@/utils/tree";

export function userEmployee() {
  const form = reactive<Employee>({
    current: 1,
    size: 20
  });
  const formRef = ref();
  const dataList = ref([]);
  const jobList = ref<Array<any>>([]);
  const deptTree = ref<Array<any>>([]);
  const loading = ref(true);
  const deptLoading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });
  const columns: TableColumnList = [
    {
      label: "工号",
      prop: "workId",
      width: 80
    },
    {
      label: "姓名",
      prop: "name",
      width: 200
    },
    {
      label: "所属部门",
      prop: "dept",
      width: 200
    },
    {
      label: "职务",
      prop: "job"
    },
    {
      label: "入职日期",
      prop: "hiredate"
    },
    {
      label: "离职日期",
      prop: "termdate"
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.status} code="Employee_Status" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getEmployeeList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: Employee) {
    addDialog({
      title: `${title}员工`,
      props: {
        formInline: {
          id: row?.id ?? "",
          deptId: row?.deptId ?? form?.deptId,
          jobId: row?.jobId ?? "",
          workId: row?.workId ?? "",
          name: row?.name ?? "",
          idCard: row?.idCard ?? "",
          phone: row?.phone ?? "",
          gender: row?.gender ?? "",
          married: row?.married ?? "",
          education: row?.education ?? "",
          salary: row?.salary ?? "",
          status: row?.status ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Employee;
        function add() {
          addEmployee(curData)
            .then(() => {
              message("员工新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`员工新增失败:${err.message}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateEmployee(curData)
            .then(() => {
              message("员工更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`员工更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function openUploadDialog() {
    addDialog({
      title: "导入",
      width: "30%",
      showClose: false,
      closeOnPressEscape: false,
      closeOnClickModal: false,
      contentRenderer: () => upload,
      footerRenderer: ({ options, index }) => (
        <el-button onClick={() => closeDialog(options, index)}>关闭</el-button>
      )
    });
  }

  function handleDelete(row: Employee) {
    deleteEmployee(row.id)
      .then(() => {
        message("员工删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`员工删除失败:${err}`, { type: "error" });
      });
  }
  function handleLeave(row: Employee) {
    leaveEmployee(row.id)
      .then(() => {
        message("员工离职成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`员工离职失败:${err}`, { type: "error" });
      });
  }

  function loadJob() {
    getJobList({ status: true, current: 1, size: 99 }).then(data => {
      jobList.value = data.records;
    });
  }

  function loadDept() {
    getDeptList({ state: true })
      .then(data => {
        deptTree.value = handleTree(data); // 处理成树结构
      })
      .finally(() => {
        deptLoading.value = false;
      });
  }

  function onSelectDept({ id, selected }) {
    if (selected) {
      form.deptId = id;
    } else {
      form.deptId = null;
    }
    onSearch();
  }

  onMounted(() => {
    loadJob();
    loadDept();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    jobList,
    deptTree,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleLeave,
    deptLoading,
    handleDelete,
    onSelectDept,
    handleSizeChange,
    handleCurrentChange,
    openUploadDialog
  };
}
